/**
 * 用户相关服务
 */
const util = require('../utils/util.js');
const api = require('../config/api.js');


/**
 * Promise封装wx.checkdwdawSession
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        console.log('ggg')
        resolve(true);
      },
      fail: function () {
        console.log("fff")
        reject(false);
      }
    })
  });
}

/**
 * Promise封装wx.login
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

/**
 * 调用微信登录
 */
function loginByWeixin(encryptedData, iv, rawData,signature,bb) {

  return new Promise(function (resolve, reject) {
    return login().then((res) => {
      console.log('asas')



      //登录远程服务器
      util.request(api.Login + "/wxb649d6629cfd387a" + "/merchant" + "/" + bb, {
        encryptedData: encryptedData,
        iv: iv,
        code:res.code
      }, 'post', {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        }).then(res => {
          console.log(res)
          if (res.code == 200) {
            //存储用户信息
            wx.setStorageSync('token', res.data.token);

            resolve(res);
          } else {
            reject(res);
          }
        })
        .catch((err) => {
          reject(err);
        });
    })
      .catch((err) => {
        reject(err);
      })
  });
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wx.getStorageSync('token')) {
      checkSession().then(() => {
        console.log('dddd')
        resolve(true);
      }).catch(() => {
        console.log('fff')
        reject(false);
      });
    } else {
      reject(false);
    }
  });
}

module.exports = {
  loginByWeixin,
  checkLogin,
};